package com.csdj.t309springboot.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * WebSocket
 */
@ServerEndpoint("/web/socket/test")//服务器终端,服务器端点
@Component
public class WebController {
    private Logger log = LoggerFactory.getLogger("");
    //静态属性属于类, 在类加载时就会创建
    private static Set<Session> sessionSet = new HashSet<>();
    /**
     * nickname存到map里作为 key,session作为值
     */
    private static Map<String,Session> sessionMap = new HashMap<>();

    /**
     * 当连接创建成功之后
     * @param session
     */
    @OnOpen
    public void onOpen(Session session) throws IOException {
        sessionSet.add(session);
        log.info("创建连接成功,session id="+session.getId());
        //获取连接并发送数据(文本,二进制)
        session.getBasicRemote().sendText("server : hello");

    }
    public void sendToAll(String nickname,String msg){
        log.info("nickname={},msg={}",nickname,msg);
        //问题:消息会发给自己
//        sessionSet.stream().forEach(session -> {
//            try{
//                //如果连接开启
//                if(session.isOpen()){
//                    session.getBasicRemote().sendText(msg);
//                }
//
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        });
//        sessionMap.entrySet().stream().forEach();
        for (Map.Entry<String, Session> entry : sessionMap.entrySet()) {
//            msg = entry.getKey();
            Session session = entry.getValue();
            System.out.println(nickname + "：" + session);
            try{
                //如果连接开启
                if(session.isOpen()){
                    session.getBasicRemote().sendText(nickname);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @OnClose
    public void onClose(Session session){
        sessionSet.remove(session);
    }
    @OnError
    public void onError(Session session,Throwable e){

    }

    /**
     * 收到服务器传来的消息; 通过session来区分客户端
     * @param session 会话对象,通过session来区分客户端
     */
    @OnMessage
    public void onMessage(String message,Session session) throws IOException {
        //获取连接并发送数据(文本,二进制)
        session.getBasicRemote().sendText(message);
    }

}
